import { _decorator, Component, instantiate, Node, RealInterpolationMode, Sprite, Vec3 } from 'cc';
import { BaseComponent } from '../../../Manager/UIManager/BaseComponent';
import { GAME_PREFAB, GAME_SPRITEFRAME, GlobalData, LevelConfig, SOUND_TYPE } from '../../../Data/GlobalData';
import { DragonBody } from './DragonBody';
import { Tools } from '../../../Tool/Tools';
import { GameScene } from '../GameScene';
const { ccclass, property } = _decorator;

@ccclass('DragonLoad')
/**
 * 龙层
 */
export class DragonLoad extends BaseComponent {

    //身体间距
    public BodySpace: number = 50;

    //龙的身体数组
    public DragonBodyArr: Node[] = [];

    //没有使用的龙的身体
    public NoUse: Node[] = [];

    //后退的龙的身体
    public BackDragonBodyArr: Node[] = [];

    //终点元素
    @property(Node)
    private EndEle: Node = null;

    //游戏场景
    @property(GameScene)
    public GameScene: GameScene = null;

    //身体层
    @property(Node)
    private BodyLoad: Node = null;

    //收藏品
    @property(Sprite)
    private Collect: Sprite = null;

    //路线
    @property(Sprite)
    private Line: Sprite = null;

    //是否复活
    public IsSave: boolean = false;
    public SaveTime: number = 1;

    protected OnShow(): void {

    }

    /**
     * 返回身体信息
     */
    public ReturnDragonBodyInfo(): number {
        let ran_num: number = Math.floor(GlobalData.DragonBodyInfo.length * Math.random());
        // ran_num = 0;
        let ran_body: number = GlobalData.DragonBodyInfo[ran_num];
        GlobalData.DragonBodyInfo.splice(ran_num, 1);
        return ran_body;
    }
    /**
     * 更新关卡信息
     */
    public UpdateLevelInfo() {

        this.Line.spriteFrame = app.resManager.SpriteFrames[GAME_SPRITEFRAME.Line + LevelConfig[GlobalData.CurrentLevel].line];
        this.Collect.spriteFrame = app.resManager.SpriteFrames[GAME_SPRITEFRAME.Collect + GlobalData.CurrentLevel]
        //
        for (let db of this.DragonBodyArr) {
            db.setParent(null);
            this.NoUse.push(db);
        }

        // 
        for (let db of this.BackDragonBodyArr) {
            db.setParent(null);
            this.NoUse.push(db);
        }

        this.BackDragonBodyArr = [];
        this.DragonBodyArr = [];

        this.FixNum = 0;
        app.pathManager.UpdatePathInfo(app.resManager.Json["level" + LevelConfig[GlobalData.CurrentLevel].line])
        this.CreateDragonBody(99);
        this.EndEle.setPosition(app.pathManager.Cuvers[app.pathManager.Cuvers.length - 1].endPoint.x, app.pathManager.Cuvers[app.pathManager.Cuvers.length - 1].endPoint.y, 0);

    }

    //计时
    public FixNum: number = 0;

    protected update(dt: number): void {

        if (GlobalData.GameOver) return;

        //创建龙的身体
        // if (GlobalData.DragonBodyInfo.length > 0) {
        //     if (!Tools.isCircleIntersect(new Vec3(app.pathManager.Cuvers[0].startPoint.x, app.pathManager.Cuvers[0].startPoint.y, 0), this.BodySpace / 2, this.DragonBodyArr[this.DragonBodyArr.length - 1].getPosition(), this.BodySpace / 2)) {
        //         this.CreateDragonBody(this.ReturnDragonBodyInfo());
        //     }
        // }



        if (this.IsSave) {
            if (this.DragonBodyArr.length > 0) {
                this.DragonBodyArr[0].getComponent(DragonBody).BackSpeed = 300;
                this.DragonBodyArr[0].getComponent(DragonBody).MoveBack(dt);
            }
            this.SaveTime -= dt;
            if (this.SaveTime <= 0) {
                this.IsSave = false;
            }
        } else {
            //创建龙的身体
            this.FixNum++;
            if (this.FixNum >= 20) {
                this.FixNum = 0;
                if (GlobalData.DragonBodyInfo.length <= 0) return;
                this.CreateDragonBody(this.ReturnDragonBodyInfo());
            }

            if (this.DragonBodyArr.length > 0) {
                this.DragonBodyArr[0].getComponent(DragonBody).MoveSelf(dt);
            }
        }

        for (let i = 1; i < this.DragonBodyArr.length; i++) {
            this.DragonBodyArr[i].getComponent(DragonBody).UpdateDistance(this.DragonBodyArr[i - 1].getComponent(DragonBody).CurrentDistance - this.BodySpace);

        }
        // for (let i = 0; i < this.DragonBodyArr.length; i++) {
        //     this.DragonBodyArr[i].getComponent(DragonBody).MoveSelf(dt);
        // }

        for (let i = 0; i < this.BackDragonBodyArr.length; i++) {
            this.BackDragonBodyArr[i].getComponent(DragonBody).MoveBack(dt);

            if (i == this.BackDragonBodyArr.length - 1) this.CehckHit(this.BackDragonBodyArr[i]);
        }
    }

    /**
     * 检测碰撞
     */
    private CehckHit(_back: Node) {
        if (this.DragonBodyArr.length == 0) return;
        // 检查与前进节点的碰
        const forwardNode = this.DragonBodyArr[0].getComponent(DragonBody);
        if (Tools.isCircleIntersect(_back.getPosition(), this.BodySpace / 2, forwardNode.node.getPosition(), this.BodySpace / 2)) {
            let _index: number = this.BackDragonBodyArr.indexOf(_back);
            this.DragonBodyArr.unshift(_back);
            _back.getComponent(DragonBody).CurrentDistance = forwardNode.CurrentDistance + this.BodySpace;
            this.BackDragonBodyArr.splice(_index, 1);

            for (let i = this.BackDragonBodyArr.length - 1; i > 0; i--) {
                if (Tools.isCircleIntersect(
                    this.BackDragonBodyArr[this.BackDragonBodyArr.length - 1].getPosition(),
                    this.BodySpace / 2 + 5,
                    this.DragonBodyArr[0].getPosition(),
                    this.BodySpace / 2 + 5
                )) {
                    this.DragonBodyArr.unshift(this.BackDragonBodyArr[this.BackDragonBodyArr.length - 1]);
                    this.BackDragonBodyArr.splice(this.BackDragonBodyArr.length - 1, 1);
                } else {
                    break;
                }

            }
        }
    }

    /**
     * 创建龙的身体
     */
    private CreateDragonBody(_index: number) {

        if (this.NoUse.length > 0) {
            let db: Node = this.NoUse.shift();
            db.getComponent(DragonBody).UpdateBodyStyle(_index);
            db.setParent(this.BodyLoad);
            db.setSiblingIndex(0);

            if (this.DragonBodyArr.length > 0) {
                db.getComponent(DragonBody).CurrentDistance = this.DragonBodyArr[this.DragonBodyArr.length - 1].getComponent(DragonBody).CurrentDistance - this.BodySpace;
            }

            this.DragonBodyArr.push(db);
            return;
        }
        let db: Node = instantiate(app.resManager.Prefabs[GAME_PREFAB.DragonBody]);
        this.BodyLoad.addChild(db);
        db.setSiblingIndex(0);
        db.getComponent(DragonBody).UpdateBodyStyle(_index);
        db.getComponent(DragonBody).DragonLoad = this;

        if (this.DragonBodyArr.length > 0) {
            db.getComponent(DragonBody).CurrentDistance = this.DragonBodyArr[this.DragonBodyArr.length - 1].getComponent(DragonBody).CurrentDistance - this.BodySpace;
        }

        this.DragonBodyArr.push(db);
    }

    /**
     * 判断消失
     */
    public CheckDisappear(_dargonbody: Node) {

        GlobalData.GameCoin += 5;

        app.audioManager.PlayEffect(SOUND_TYPE.Hit);
        let clear_index: number = this.DragonBodyArr.indexOf(_dargonbody);

        if (clear_index == -1) {
            let clear_index1: number = this.BackDragonBodyArr.indexOf(_dargonbody);
            this.BackDragonBodyArr[clear_index1].setParent(null);
            this.NoUse.push(this.BackDragonBodyArr[clear_index1]);
            this.BackDragonBodyArr.splice(clear_index1, 1);
        } else {
            this.DragonBodyArr[clear_index].setParent(null);
            this.NoUse.push(this.DragonBodyArr[clear_index]);
            this.DragonBodyArr.splice(clear_index, 1);
            for (let i = 0; i < clear_index; i++) {
                let db: Node = this.DragonBodyArr.shift();
                db.getComponent(DragonBody).BackSpeed = 150;
                this.BackDragonBodyArr.push(db);
            }
        }

        //
        if (this.DragonBodyArr.length == 0 && GlobalData.DragonBodyInfo.length == 0) {
            this.DragonBodyArr.push(this.BackDragonBodyArr[this.BackDragonBodyArr.length - 1]);
            this.BackDragonBodyArr.splice(this.BackDragonBodyArr.length - 1, 1);
        }


        //判断游戏过关
        if (GlobalData.DragonBodyInfo.length == 0 && this.DragonBodyArr.length + this.BackDragonBodyArr.length == 1) {
            this.GameScene.GamePass();
        }


    }

}



